package org.jf.tool.fx.jftoolfx.util;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * 非对称加解密工具类
 *
 * @author jifeng_zhang
 * @date 2025/8/29 下午4:49
 */
public class AsymmetricUtil {

    public static enum TYPE {
        RSA("RSA"),

        SM2("SM2");

        private final String name;


        TYPE(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }

    public static byte[] encrypt(AsymmetricUtil.TYPE type, String publicKey, byte[] plain) throws Exception {
        String transformation = String.format("%s/%s/%s", type.getName(), "ECB", "PKCS1Padding");
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.ENCRYPT_MODE, loadPublicKey(publicKey));
        return cipher.doFinal(plain);
    }

    /**
     * 从Base64字符串加载公钥
     *
     * @param base64PublicKey
     * @return
     * @throws Exception
     */
    public static PublicKey loadPublicKey(String base64PublicKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(base64PublicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        return keyFactory.generatePublic(keySpec);
    }

    // 从Base64字符串加载私钥
    public static PrivateKey loadPrivateKey(String base64PrivateKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(base64PrivateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        return keyFactory.generatePrivate(keySpec);
    }
}
